package com.ssm.wzl.controller;

import com.ssm.wzl.po.Items;
import com.ssm.wzl.po.Person;
import com.ssm.wzl.po.User;
import com.ssm.wzl.service.ItemService;
import com.ssm.wzl.service.UserService;
import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2017/5/17 0017.
 */
@Controller
@RequestMapping("/list")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private ItemService itemService;
    @RequestMapping("/index")
    public String cindex(HttpServletRequest request, Model model) throws Exception{
        List<Items> mlist = userService.findList();
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.addObject("user",mlist.get(0).toString());
//        modelAndView.setViewName("/index");
        model.addAttribute("itemList",mlist);
        return "/itemList";
    }


    @RequestMapping("/addOrder")
    @ResponseBody
    public ResponseEntity addList(@RequestParam("name") String name,@RequestParam("price") String price,
                          @RequestParam("detail") String detail, @RequestParam("date") String date,HttpServletRequest request,Model model)throws Exception{
//        String name = request.getParameter("name");
//        String price = request.getParameter("price");
//        String detail = request.getParameter("detail");
//        String date = request.getParameter("date");
        Items items = new Items();
        items.setName(name);
        items.setPrice(Float.parseFloat(price));
        items.setDetail(detail);
        items.setCreatetime(new Date());
        itemService.addList(items);

        return new ResponseEntity(HttpStatus.OK);
    }

    @RequestMapping(value = "/testJson",method = RequestMethod.GET)
    public @ResponseBody ResponseEntity<Map<String,String>> testJson(HttpServletRequest request){
//        Enumeration<String> head = request.getHeaderNames();
//        while (head.hasMoreElements()){@RequestBody HashMap<String,String> name,
//            System.out.println(head.nextElement());
//        }
//        Enumeration<String> aa = request.getParameterNames();
        System.out.println(request.getParameter("name"));


//        System.out.println(name);
//        String na = (String) session.getAttribute("name");

//        String maname = request.getParameter("name");
//        Map<String,String[]> map = request.getParameterMap();
//        for (Map.Entry<String,String> mm : map.entrySet()){
//            System.out.println("key = " + mm.getKey()+" , value = "+ mm.getValue());
//        }
        HashMap<String,String> result = new HashMap<String, String>();
        result.put("name","这是后台修改的");
        result.put("detail","从后台输入的地址");
//        user.setName("这是个后台修改后的");
//        user.setDetail("从后台输入的地址");
        return new ResponseEntity<Map<String, String>>(result, HttpStatus.OK);

    }

//    @RequestMapping("/testJson")
//    public String testJson(String str){
//        System.out.println(str);
////        user.setUsername("这是个后台修改后的");
////        user.setAddress("从后台输入的地址");
//        return "";
//
//    }

    @RequestMapping("/itemEdit/{id}")
    public String itemEdit(@PathVariable("id") Integer id,HttpServletRequest request, Model model) throws Exception{
        Items items = itemService.findItemById(id);
        model.addAttribute("item",items);
        return "/editItem";
    }



    @RequestMapping("/regist")
    @ResponseBody
    public ResponseEntity<Map<String,Object>> regist(@RequestBody Person params) throws Exception{
        HashMap<String,Object> map = new HashMap<String,Object>();
        if (isEmpty(params.getName()) || isEmpty(params.getPassword())){
            map.put("code","002");
            map.put("msg","少传参数");
        }else {
            Person son = userService.findPerson(params.getName());
            if (son == null){
                userService.insertPerson(params);
                map.put("code","000");
                map.put("msg","注册成功");
            }else {
                map.put("code","003");
                map.put("msg","用户已存在");
            }
        }
        return new ResponseEntity<Map<String, Object>>(map,HttpStatus.OK);
    }




    @RequestMapping("/testRequest")
    public ModelAndView testRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String agent = request.getHeader("User-Agent").toLowerCase();
        System.out.println("响应头的类型："+agent);
        if (agent.indexOf("micromessenger") > 0) {
            System.out.println("微信支付");
            response.setContentType("textml;charset=UTF-8");
//            response.sendRedirect("wxp://f2f0Fdi-uTYc8NpmgA4GYUC-R9u1XUdDog1b");
        } else if (agent.indexOf("alipayclient") > 0) {
            System.out.println("阿里支付");

//            String form = testService.aliPay();
//            response.setContentType("textml;charset=UTF-8");
//            response.getWriter().write(form);//直接将完整的表单html输出到页面
//            response.getWriter().flush();
//          response.sendRedirect("/ali.html");
//            response.sendRedirect();
            response.setContentType("textml;charset=UTF-8");
//            response.sendRedirect("wxp://f2f0Fdi-uTYc8NpmgA4GYUC-R9u1XUdDog1b");


        }
//        response.sendRedirect("http://www.baidu.com");
        System.out.println("请求来了");
        ModelAndView and = new ModelAndView(new RedirectView("wxp://f2f0Fdi-uTYc8NpmgA4GYUC-R9u1XUdDog1b"));

        return and;

    }



    @RequestMapping("/login")
    @ResponseBody
    public ResponseEntity<Map<String,Object>> login( @RequestBody Person person) throws Exception{
        HashMap<String,Object> params = new HashMap<String, Object>();
        Person pp = userService.findPerson(person.getName());
        if (pp == null){
            params.put("code","002");
            params.put("msg","用户不存在");

        }else {
            if (pp.getPassword().equals(person.getPassword())){
                params.put("name",pp.getName());
                params.put("id",pp.getId());
                params.put("nickname",pp.getNickname());
                params.put("sex",pp.getSex());
                params.put("age",pp.getAge());
                params.put("address",pp.getAddress());

            }else {
                params.put("code","003");
                params.put("msg","密码错误");
            }
        }
        return new ResponseEntity<Map<String, Object>>(params,HttpStatus.OK);
    }

    @RequestMapping("/updateitem")
    public String upload(MultipartFile pictureFile,Items items,Model model,HttpServletRequest request)throws Exception{

        String fileStr = pictureFile.getOriginalFilename();
        String newFileName = UUID.randomUUID().toString()+fileStr.substring(fileStr.lastIndexOf("."));
        pictureFile.transferTo(new File("D:\\Tomcat\\apache-tomcat-7.0.75\\webapps\\image-web\\upload\\"+newFileName));
        items.setPic(newFileName);
        itemService.updateItems(items);

        return "redirect:itemEdit/"+items.getId()+".action";


    }


    private boolean isEmpty(String str){
        if (str == null || str.length() == 0){
            return true;
        }
        return false;
    }

}
